<template>
  <span class="import-file">
    <el-button size="small" v-show="props.templateUrl" type="primary"
      @click="handleCommand('', 'templateDownload')">下载模板</el-button>
    <el-button :type="props.type" :size="props.size" @click="handleCommand('', 'importFile')">
      <slot>{{ props.btnTxt }}</slot>
    </el-button>
    <slot name="extra"></slot>
    <el-upload v-show="false" ref="upFileRef" action="/" :accept="props.accept" :http-request="bindUpFileFun"
      :file-list="fileList">
      <el-button ref="importFileBtnRef" size="small" type="primary">点击上传</el-button>
    </el-upload>
  </span>
</template>
<script setup name="importUploadFile">
import { ElMessage } from 'element-plus';
import { saveAs } from 'file-saver'
function saveAsFile(res, fileName, loading) {
  if (typeof res === 'string') {
    saveAs(res, fileName)
    loading && loading.close()
  } else {
    if (res.data.size < 100 && res.data.type === 'application/json') {
      const read = new FileReader()
      read.addEventListener('load', () => {
        loading && loading.close()
        let text = read.result
        text = JSON.parse(text)
        Message.error(text.desc)
      }, false)
      read.readAsText(res.data, 'utf-8')
    } else {
      loading && loading.close()
      saveAs(res.data, fileName)
    }
  }
}
const props = defineProps({
  btnTxt: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: 'danger'
  },
  size: {
    type: String,
    default: 'small'
  },
  accept: {
    type: String,
    default: '.xls,.xlsx'
  },
  tip: {
    type: String,
    default: '文件导入中....'
  },
  otherData: {
    type: Object,
    default: () => ({})
  },
  templateUrl: {
    type: String,
    default: ''
  },
  fileName: {
    type: String,
    default: ''
  },
  request: Function
})
const fileList = reactive([])
const importFileBtnRef = ref(null)
const upFileRef = ref(null)
function handleCommand(r, t) {
  switch (t) {
    case 'importFile':
      if (props.request) {
        importFileBtnRef.value.$el.click()
      } else {
        ElMessage.error('请先绑定上传接口！')
      }
      break
    case 'templateDownload':
      saveAsFile(props.templateUrl, props.fileName)
      break
    default:
      ElMessage.error('敬请期待！')
      break
  }
}
function bindUpFileFun(option) {
  const loading = this.$loading({
    lock: true,
    text: props.tip,
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const form = new FormData()
  const backProgress = (e) => {
    if (e.total > 0) {
      e.percent = e.loaded / e.total * 100
    }
    // option.onProgress(e)
  }
  for (const key in props.otherData) {
    form.append(key, props.otherData[key])
  }
  form.append('file', option.file)
  props.request(form, process.env.VUE_APP_BASE_URL, backProgress).then(res => {
    const data = res.data
    if (data.code !== 'rest.success') {
      ElMessage.error(data.desc)
    } else {
      ElMessage.success('导入成功！')
      emit('importEnd')
    }
    loading.close()
    upFileRef.value.clearFiles()
  }).catch(() => {
    loading.close()
    upFileRef.value.clearFiles()
  })
} 
</script>
<style lang='scss' scoped>
.import-file {
  display: inline-block;
  vertical-align: middle;
}
</style>
